import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { emitter } from "@/utils/mitt";
import { checkedInput } from "@/utils/public/regular"
import { SpliceDate } from "@/utils/public/method"
import { ref, reactive, nextTick, watch, onMounted, onBeforeUnmount } from "vue";
import {
  proncdgetlist,
  profixpriceFixPrice,
  ProFixPriceGetSearch,
  ProFixPriceGetCarOBD,
  ProFixPriceGetInsure,
  ProFixPriceGetDetail,
  profixpriceFixPriceSend,
  ProFixPriceInsertFixPrice
} from "@/api/stu/InsuranceData"
import qs from "qs";
export function useAutoInsurance() {
  const route = useRoute();
  const columns = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "模型名称",
      prop: "fName",
    },
    {
      label: "新建时间",
      prop: "createTime",
      cellRenderer: ({ row }) => (
        SpliceDate(row.createTime)
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];
  const columns2 = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "出险次数",
      prop: "name",
    },
    {
      label: "NCD等级",
      prop: "ncdLv",
    },
    {
      label: "系数",
      prop: "ncdCoef",
    }
  ];
  const dataLists1 = ref([]);
  const SeletectData = ref([]);//
  const SelectData = ref(); // 选中的数据
  const StubimForm = reactive({
    fName: "",
    createTime: "",
    detail: [],
  })
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [10, 30, 50, 100],
    background: true
  });
  const dataList = ref([]);
  const loading = ref(false);
  const btnloading = ref<boolean>(false);
  const InsureList = ref([]);//保单列表
  const DialogVisible = ref<boolean>(false);
  const DialogVisibles = ref<boolean>(false);
  const car_insurance_item = ref<any>({
    piNumber: "",
    ppName: "",
    piApplicant: "",
    applicantAge: "",
    applicantSex: "",
    carType: "",
    carUse: "",
    foundAmount: null,
    seatTonnage: "",
    carUseYear: "",
    buyCarPrice: "",
    count: "",
    applyTime: "",
    ncdCoef: "",
    child: [],
    pType: "",
  });
  const sendDate = ref();
  const seal = ref(0)
  const stroage = reactive({
    FId: "",
    PIId: "",
    PINumber: ""
  });//存储搜索保单数据内容
  // 定价
  async function ViewDisgen(row) {
    if (!row.isSave) {
      stroage.FId = row.id;
      DialogVisibles.value = true;
    } else {
      const data = {
        SendTime: row.createTime,//  发送时间
        FId: row.id,//  定价模型Id
        PIId: row.piId,//  投保Id
      };
      const res = await profixpriceFixPriceSend(qs.stringify(data));
      if (res.success) {
        ElMessage.success(res.msg);
        GetDataList()
      } else {
        ElMessage.error(res.msg)
      }
    }

  }

  // 获取保单号并进行搜索
  async function changeinsurance(row) {
    stroage.PIId = row.piId;
    stroage.PINumber = row.piNumber;
    const res = await ProFixPriceGetDetail(qs.stringify(stroage));
    if (res.success) {
      car_insurance_item.value = res.data;
    } else {
      ElMessage.error(res.msg)
      close_forms()
    }

  }

  // 新增定价模型 open
  function StubimMark() {
    emitter.emit("StubimToFather")
  };

  // 通过子组件数据回调
  emitter.on("StubimToFatherData", async (data) => {

    const datas = {
      "taskId": route.query.taskId,
      "planId": route.query.planId,
      ...StubimForm,
      ...{ detail: data }
    }
    for (let key in datas) {
      if (datas[key] === '' || !datas['detail'].length) {
        ElMessage.warning("请填完所有选项");
        return;
      }
    }
    btnloading.value = true;
    const res = await ProFixPriceInsertFixPrice(datas);
    if (res.success) {
      ElMessage.success(res.msg);
      GetDataList()
      Close_form()
      btnloading.value = false;
    } else {
      ElMessage.error(res.msg)
      setTimeout(() => { btnloading.value = false; }, 1500)
    }
  })

  // 关闭弹窗
  function Close_form() {
    DialogVisible.value = false;
    StubimForm.createTime = "";
    StubimForm.detail = [];
    StubimForm.fName = "";
    SelectData.value = []
  }

  function close_forms() {
    DialogVisibles.value = false;
    seal.value = 0;
    sendDate.value = "";
    stroage.PINumber = "";
    car_insurance_item.value = {
      piNumber: "",
      ppName: "",
      piApplicant: "",
      applicantAge: "",
      applicantSex: "",
      carType: "",
      carUse: "",
      seatTonnage: "",
      carUseYear: "",
      buyCarPrice: "",
      count: "",
      applyTime: "",
      child: [],
      pType: "",
    };
  }
  // 新增定价模型 end
  // 提交发送定价
  async function StubimMarks() {
    if (stroage.PINumber == "") { ElMessage.warning("请选择保单号"); return; }
    if (!sendDate.value) { ElMessage.warning("请选择发送时间"); return; }
    if (!seal.value) { ElMessage.warning("请盖章"); return; }
    btnloading.value = true;
    const data = {
      "taskId": route.query.taskId,
      "planId": route.query.planId,
      PIId: car_insurance_item.value.piId,  //投保Id
      FId: stroage.FId,  //定价模型Id
      FinalPrice: car_insurance_item.value.finalPrice,  //最终保费
      NCDCoef: car_insurance_item.value.ncdCoef, //NCD系数
      TVCoef: 1.0,  //交通违法系数
      ActCoef: car_insurance_item.value.actCoef,  //自主定价系数
      PriceTime: sendDate.value,  //发送时间
      piApplicant: car_insurance_item.value.piApplicant,
      ppName: car_insurance_item.value.ppName,
    };
    const res = await profixpriceFixPrice(data);
    if (res.success) {
      ElMessage.success(res.msg);
      close_forms()
      GetDataList()
      btnloading.value = false;
    } else {
      setTimeout(() => { btnloading.value = false; }, 1500)
      ElMessage.error(res.msg)
    }
  }
  function handleSizeChange(val) { GetDataList() }
  function handleCurrentChange(val) { GetDataList() }
  async function GetSeletectDataList() {
    const res = await ProFixPriceGetCarOBD()
    if (res.success) {
      SeletectData.value = res?.data;
    } else {
      ElMessage.error(res.msg)
    }
  }
  // 获取模型数据列表
  async function GetDataList() {
    const data = {
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize,
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    }
    const res = await ProFixPriceGetSearch(data);
    if (res.success) {
      dataList.value = res.data?.items;
      pagination.total = res.data?.totalCount
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 获取保单号列表
  async function GetInsureList() {
    const data = qs.stringify({
      "taskId": route.query.taskId,
      "planId": route.query.planId,
    })
    const res = await ProFixPriceGetInsure(data)
    if (res.success) {
      InsureList.value = res?.data;
    } else {
      ElMessage.error(res.msg)
    }
  }
  async function Getproncdgetlist() {
    const res = await proncdgetlist();
    if (res.success) {
      dataLists1.value = res?.data;
    } else {
      ElMessage.error(res.msg)
    }
  }
  onBeforeUnmount(() => {
    emitter.off("StubimToFatherData")
  })
  onMounted(() => {
    GetDataList()
    GetInsureList()
    Getproncdgetlist()
    GetSeletectDataList()
  })
  return {
    seal,
    sendDate,
    stroage,
    columns,
    columns2,
    dataLists1,
    pagination,
    dataList,
    loading,
    btnloading,
    InsureList,
    StubimForm,
    SelectData,
    SeletectData,
    DialogVisible,
    DialogVisibles,
    car_insurance_item,
    StubimMark,
    Close_form,
    close_forms,
    StubimMarks,
    ViewDisgen,
    changeinsurance,
    handleSizeChange,
    handleCurrentChange
  }
}
